<template>
  <div class="login">
    <div>
      <div class="box">
        <div class="loginimg">
          <el-tabs
            v-model="activeName"
            class="demo-tabs"
            @tab-click="handleClick"
          >
            <el-tab-pane label="登录" name="login">
              <el-form
                class="form"
                ref="loginFormRef"
                :model="loginForm"
                :rules="loginRules"
              >
                <el-form-item prop="username">
                  <el-input
                    v-model="loginForm.username"
                    placeholder="输入用户名"
                  >
                    <template #prepend
                      ><el-icon> <User /> </el-icon
                    ></template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="phone">
                  <el-input
                    v-model="loginForm.phone"
                    placeholder="输入手机号"
                  >
                    <template #prepend
                      ><el-icon> <User /> </el-icon
                    ></template>
                  </el-input>
                </el-form-item>
                <el-form-item style="margin-top: 20px" prop="password">
                  <el-input v-model="loginForm.password" placeholder="输入密码">
                    <template #prepend
                      ><el-icon> <Lock /> </el-icon
                    ></template>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    style="width: 400px; height: 40px"
                    @click="submitLoginForm(loginFormRef)"
                    >登录</el-button
                  >
                </el-form-item>
              </el-form>
              <h4 style="color: #ccc; margin-left: 43px">
                用户名: admin &nbsp;&nbsp;&nbsp; 密码: 123456
              </h4>
            </el-tab-pane>
            <el-tab-pane class="form" label="注册" name="register">
              <el-form
                class="form"
                ref="registerFormRef"
                :model="registerForm"
                :rules="registerRules"
              >
                <el-form-item
                  prop="username"
                  style="margin-top: -40px; width: 400px; margin-left: -40px"
                >
                  <el-input
                    v-model="registerForm.username"
                    placeholder="输入用户名"
                  >
                    <template #prepend
                      ><el-icon> <User /> </el-icon
                    ></template>
                  </el-input>
                </el-form-item>
                <el-form-item
                  style="margin-top: -20px; width: 400px; margin-left: -40px"
                  prop="password"
                >
                  <el-input v-model="registerForm.password" placeholder="输入密码">
                    <template #prepend
                      ><el-icon> <Lock /> </el-icon
                    ></template>
                  </el-input>
                </el-form-item>
                <el-form-item
                  style="margin-top: -20px; width: 400px; margin-left: -40px"
                  prop="password"
                >
                  <el-input v-model="registerForm.confirmPassword" placeholder="确认密码">
                    <template #prepend
                      ><el-icon> <Lock /> </el-icon
                    ></template>
                  </el-input>
                </el-form-item>
                <el-form-item
                  label="手机号码"
                  style="margin-top: -20px; width: 400px; margin-left: -40px"
                >
                  <el-row gutter="0">
                    <el-col :span="16">
                      <el-input
                        v-model="registerForm.phone"
                        placeholder="请输入手机号码"
                      />
                    </el-col>
                    <el-col :span="8">
                      <el-button style=" width: 120px; height: 40px;" @click="verifyCode">发送验证码</el-button>
                    </el-col>
                  </el-row>
                </el-form-item>

                <el-form-item
                  label="验证码"
                  style="margin-top: -25px; width: 400px; margin-left: -40px"
                >
                  <el-input v-model="registerForm.code" />
                </el-form-item>
                <el-form-item>
                  <el-button
                    type="primary"
                    style="
                      width: 440px;
                      height: 40px;
                      margin-left: -40px;
                      margin-top: -20px;
                      margin-right: -40px;
                    "
                    @click="submitregisterForm(registerFormRef)"
                    >注册</el-button
                  >
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { User, Lock, Phone } from "@element-plus/icons-vue";
import { ref, reactive } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import type { TabsPaneContext } from "element-plus";
import { useRouter } from "vue-router";
import { useLoginStore } from "@/stores/login";
import { jwtDecode } from "jwt-decode";
import { checkPass } from "../assets/js/utils";
import axios from "../assets/js/axios";
const SmsCode = ref<any>([]);
const loginStore = useLoginStore();
const router = useRouter();
const loginFormRef = ref<FormInstance>();
const registerFormRef = ref<FormInstance>();

// 登录表单和注册表单的数据
const loginForm = reactive({
  username: "",
  phone:"",
  password: "",
});

const registerForm = reactive({
  username: "",
  password: "",
  confirmPassword:"",
  phone: "",
  code: "",
});

let activeName = ref('login')

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

// 初始化时生成验证码

// 当前激活的 Tab

// 表单验证规则
const loginRules = reactive<FormRules>({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
    
    {
      min: 2,
      max: 20,
      message: "用户名需要在2到20的长度",
      trigger: "blur",
    },
  ],
 
  password: [
    {
      required: true,
      validator: checkPass,
      trigger: "blur",
    },
  ],
 
});

const registerRules = reactive<FormRules>({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
    {
      min: 2,
      max: 20,
      message: "用户名需要在2到20的长度",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      validator: checkPass,
      trigger: "blur",
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: "请确认密码",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur",
    },
    ],
    code:[{
      required: true,
      message: "请输入验证码",
      trigger: "blur",
    }]
  
});


// 登录提交表单
const submitLoginForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post("/serviceedu/edu-user/login", loginForm).then((res: any) => {
        if (res.code === 200) {
          // 调试输出
          console.log("Login response:", res);
          loginStore.changeUserInfo(res.data);
          localStorage.setItem("userToken", res.data.token); // 确保 token 被保存
          localStorage.setItem("userInfo", JSON.stringify(res.data)); 
          router.push("/");
        } else {
          ElMessage({
            type: "error",
            message: res.msg,
          });
        }
      });
    } else {
      console.log("提交表单错误！", fields);
    }
  });
};

// 验证码获取
const verifyCode = () => {
  axios.get(`/servicesms/sms/get/${registerForm.phone}`,{})
    .then((res: any) => {
      // 验证码获取成功
      SmsCode.value = res.data.code; // 确保这里赋值的是字符串
      ElMessage.success("验证码已发送");
    })
    .catch((error) => {
      ElMessage.error("验证码发送失败");
      console.error(error);
    });
};

const submitregisterForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    console.log(formEl);
    return;
  }
  if(registerForm.password!==registerForm.confirmPassword){
    ElMessage({
      type: "error",
      message: "请输入正确的密码"
    });
    return;
  }
  // 检查验证码是否为空
  if (!registerForm.code) {
    ElMessage({
      type: "error",
      message: "验证码不能为空"
    });
    return;
  }
  // 检查输入的验证码和存储的验证码是否相同
  if (registerForm.code.toString()!== SmsCode.value) {
    ElMessage({
      type: "error",
      message: "验证码错误"
    });
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post("/serviceedu/edu-user/Register", registerForm).
        then((res: any) => {
          console.log(registerForm.code+registerForm.password+registerForm.phone+registerForm.username);
          if (res.code === 200) {
            loginStore.changeUserInfo(registerForm);
            localStorage.setItem("userToken", res.data.token); // 确保 token 被保存
            localStorage.setItem("userInfo", JSON.stringify(registerForm));
            ElMessage({
              type: "success",
              message: "注册成功"
            });

          } else {
            ElMessage({
              type: "error",
              message: res.msg
            });
          }
        })
        .catch((error) => {
    ElMessage.error("注册失败：" + error.response.data.msg);
    console.error("注册失败详情:", error.response);
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};

</script>

<style scoped lang="less">
.login {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-color: #eef0f3;

  .box {
    width: 500px;
    position: absolute;
    left: 50%;
    top: 50%;
    background: white;
    border-radius: 8px;
    transform: translate(-50%, -50%);
    height: 440px;
    overflow: hidden;
    box-shadow: 0 6px 20px 5px #9898981a, 0 16px 24px 2px #75757524;
  }

  :deep .el-tabs__item {
    align-items: center;
    box-sizing: border-box;
    color: var(--el-text-color-primary);
    display: flex;
    font-size: var(--el-font-size-base);
    font-weight: 500;
    height: var(--el-tabs-header-height);
    justify-content: center;
    list-style: none;
    padding: 0 20px;
    position: relative;
    width: 250px;
    height: 75px;
  }
}

.form {
  width: 80%;
  margin: 50px auto 15px;

  .el-input {
    margin-bottom: 20px;
  }

  .password-icon {
    cursor: pointer;
    color: #409eff;
  }
}

.fixed-top-right {
  position: absolute;
  top: 10px;
  right: 10px;
}

.el-form {
  :deep .el-input__wrapper {
    height: 40px;
    border-bottom: 1px solid #cccccc;
  }

  :deep .el-form-item__error {
    left: 70px;
    top: 40px;
  }
}
</style>
